﻿using DevExpress.Mvvm;
using DevExpress.Mvvm.Native;
using DevExpress.Xpf.Grid;
using DevExpress.XtraPrinting;
using DevExpress.XtraRichEdit.Layout;
using FastExpressionCompiler.LightExpression;
using HandyControl.Controls;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using PlaceOrder_Client.Converters;
using PlaceOrder_Client.Models.Common;
using PlaceOrder_Client.Views;
using PlaceOrder_Core.Helper;
using PlaceOrder_Core.Models.QuanYi;
using PlaceOrder_Core.Services.Instances;
using PlaceOrder_Core.Services.Interfaces;
using PlaceOrder_Shared.Helpers;
using PlaceOrder_Shared.Models.Common;
using Prism.DryIoc;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using MessageBox = HandyControl.Controls.MessageBox;

namespace PlaceOrder_Client.ViewModels
{
    /// <summary>
    /// 当前持仓页面的vm
    /// </summary>
    public class OnHoldPositionsViewModel:Prism.Mvvm.BindableBase
    {
        #region 依赖属性
        /// <summary>
        /// 加载中
        /// </summary>
        private bool isLoading;

        public bool IsLoading
        {
            get { return isLoading; }
            set { isLoading = value; RaisePropertyChanged(); }
        }


        /// <summary>
        /// 加载显示的东西
        /// </summary>
        private string loadingMessage = "加载中...";

        public string LoadingMessage
        {
            get { return loadingMessage; }
            set { loadingMessage = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<WeiYueChildTrade> weiYueTrades;

        public ObservableCollection<WeiYueChildTrade> WeiYueTrades
        {
            get { return weiYueTrades; }
            set { weiYueTrades = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<YiPingLilyTrade> yiPingOrder;

        public ObservableCollection<YiPingLilyTrade> YiPingOrder
        {
            get { return yiPingOrder; }
            set { yiPingOrder = value; RaisePropertyChanged(); }
        }


        /// <summary>
        /// 对冲Order（已平包括的即同券、反向、同交割、同价格）
        /// </summary>
        private ObservableCollection<YiPingLilyTrade> duiChongOrder;

        public ObservableCollection<YiPingLilyTrade> DuiChongOrder
        {
            get { return duiChongOrder; }
            set { duiChongOrder = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<PingCangLilyTrade> weiPingOrder;

        public ObservableCollection<PingCangLilyTrade> WeiPingOrder
        {
            get { return weiPingOrder; }
            set { weiPingOrder = value; RaisePropertyChanged(); }
        }
        /// <summary>
        /// 点击未平触发
        /// </summary>
        private bool isNotPingCangSelected=true;

        public bool IsNotPingCangSelected
        {
            get { return isNotPingCangSelected; }
            set { isNotPingCangSelected = value; }
        }


        /// <summary>
        /// 点击已平触发
        /// </summary>
        private bool isPingCangSelected = false;

        public bool IsPingCangSelected
        {
            get { return isPingCangSelected; }
            set { isPingCangSelected = value; }
        }

        /// <summary>
        /// 未平买仓
        /// </summary>
        private decimal weiPingbuyVolume;

        public decimal WeiPingBuyVolume
        {
            get { return weiPingbuyVolume; }
            set { weiPingbuyVolume = value;RaisePropertyChanged(); }
        }


        /// <summary>
        /// 未平买仓
        /// </summary>
        private decimal weiPingSellVolume;

        public decimal WeiPingSellVolume
        {
            get { return weiPingSellVolume; }
            set { weiPingSellVolume = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 已平买仓
        /// </summary>
        private decimal yiPingbuyVolume;

        public decimal YiPingBuyVolume
        {
            get { return yiPingbuyVolume; }
            set { yiPingbuyVolume = value; RaisePropertyChanged(); }
        }


        /// <summary>
        /// 已平卖仓
        /// </summary>
        private decimal yiPingSellVolume;

        public decimal YiPingSellVolume
        {
            get { return yiPingSellVolume; }
            set { yiPingSellVolume = value; RaisePropertyChanged(); }
        }


        /// <summary>
        /// 对冲买仓
        /// </summary>
        private decimal duiChongbuyVolume;

        public decimal DuiChongBuyVolume
        {
            get { return duiChongbuyVolume; }
            set { duiChongbuyVolume = value; RaisePropertyChanged(); }
        }


        /// <summary>
        /// 已平卖仓
        /// </summary>
        private decimal duiChongSellVolume;

        public decimal DuiChongSellVolume
        {
            get { return duiChongSellVolume; }
            set { duiChongSellVolume = value; RaisePropertyChanged(); }
        }
        /// <summary>
        /// 未平盈亏显示
        /// </summary>
        private decimal weiPingyingKui;

        public decimal WeiPingYingKui
        {
            get { return weiPingyingKui; }
            set { weiPingyingKui = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 已平盈亏显示
        /// </summary>
        private decimal yiPingyingKui;

        public decimal YiPingYingKui
        {
            get { return yiPingyingKui; }
            set { yiPingyingKui = value; RaisePropertyChanged(); }
        }


        /// <summary>
        /// 已平盈亏显示
        /// </summary>
        private decimal duiChongYingKui;

        public decimal DuiChongYingKui
        {
            get { return duiChongYingKui; }
            set { duiChongYingKui = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<string> holdType;

        public ObservableCollection<string> HoldType
        {
            get { return holdType; }
            set { holdType = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 0-全部，1-待平仓，2-已平仓
        /// </summary>
        private int selectedHoldTypeIndex=1;

        public int SelectedHoldTypeIndex
        {
            get { return selectedHoldTypeIndex; }
            set { selectedHoldTypeIndex = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<UserTrade> onHoldDataList;

        public ObservableCollection<UserTrade> OnHoldDataList
        {
            get { return onHoldDataList; }
            set { onHoldDataList = value;RaisePropertyChanged(); }
        }


        private ObservableCollection<PingCangLilyTrade> onHoldPingCangLilyList;

        public ObservableCollection<PingCangLilyTrade> OnHoldPingCangLilyList
        {
            get { return onHoldPingCangLilyList; }
            set { onHoldPingCangLilyList = value; RaisePropertyChanged(); }
        }
        #endregion

        #region 命令
        
        public DelegateCommand<string> ExportCommand { get; set; }

        public DelegateCommand<PingCangLilyTrade> OpenPingCangViewCommand { get; set; }
        public DelegateCommand HoldTypeSelectionChangedCommand { get; set; }
        public DelegateCommand<string> SearchCommand { get; set; }
        public DelegateCommand<YiPingLilyTrade> ReviewCommand { get; set; }

        public DelegateCommand TestCommand1 { get; set; }
        public DelegateCommand TestCommand2 { get; set; }

        #endregion
        private readonly IDailyData _dailyData;
        public OnHoldPositionsViewModel(IDailyData dailyData)
        {
            _dailyData = dailyData;
            
            SelectedHoldTypeIndex = 1;//默认显示待平仓的
            HandleRefreshAll();
            InitCommand();

            // 注册接收 orderlistview返回的 平仓消息的方法
            Messenger.Default.Register<QuanYiOrderServerResponseClass>(this, MessageToken.PingCangMessage, HandlePingCangMessage);

            Messenger.Default.Register<string>(this, MessageToken.RefreshCang, HandleRefreshAll);

            // 注册消息处理程序
            Messenger.Default.Register<string>(this, MessageToken.RefreshWeiPing, HandleRefreshWeiPing);
        }
        private object _lockObj = new object();
        private void HandleRefreshWeiPing(string obj)
        {
            lock(_lockObj)
            {
                InitWeiPingValueAsync();//未平单
            }
     

        }

        private async void HandleRefreshAll(string obj=null)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            try
            {
                IsLoading = true;
                await InitValueAsync();
            }
            catch(Exception ex)
            {
                AppLog.WriteError("持仓界面HandleRefreshAll异常" + ex.StackTrace + ex.Message);
            }
            finally
            {
                IsLoading = false;
            }
            stopwatch.Stop();
            AppLog.WriteInfo($"HandleRefreshAll 方法耗时: {stopwatch.ElapsedMilliseconds} 毫秒");
        }

        private void HandlePingCangMessage(QuanYiOrderServerResponseClass qsr)
        {
            try
            {
                HandyControl.Controls.MessageBox.Show(qsr.Message);
            }catch(Exception ex)
            {

            }
        }

        private void InitCommand()
        {
            OpenPingCangViewCommand = new(OpenPingCangViewHandle);
            //HoldTypeSelectionChangedCommand = new(SearchHandle);

            SearchCommand = new DelegateCommand<string>(SearchHandle);

            ExportCommand = new DelegateCommand<string>(ExportHandle);

            ReviewCommand = new DelegateCommand<YiPingLilyTrade>(Review);

            TestCommand1 = new DelegateCommand(() =>
            {
                if(this.WeiPingOrder!=null)
                {
                    this.WeiPingOrder.Clear();
                    this.WeiPingOrder = null;
                    this.WeiPingBuyVolume = 0;
                    this.WeiPingSellVolume = 0;
                    this.WeiPingYingKui = 0;
                }
               
            });

            TestCommand2 = new DelegateCommand(() =>
            {
                if(this.YiPingOrder!=null)
                {
                    this.YiPingOrder.Clear();
                    this.YiPingOrder = null;
                    this.YiPingBuyVolume = 0;
                    this.YiPingSellVolume = 0;
                    this.YiPingYingKui = 0;
                }
             
            });
        }
        private bool blocking = false;
        private void Review(YiPingLilyTrade trade)
        {
            try
            {
                if (blocking)
                {
                    Growl.WarningGlobal("有正在执行的任务");
                    return;
                }
                blocking = true;
                var viewModel = new RequestReviewViewModel(trade);
                var parentWindow = PrismApplication.Current.Windows.OfType<OnHoldPositionsView>().FirstOrDefault(w => w.IsActive);

                //var parentWindow = PrismApplication.Current.MainWindow;
                //selectedUserTrade = new UserTrade(userTrade);
                // 创建新窗口并设置DataContext
                var window = new RequestReviewView
                {
                    DataContext = viewModel,
                    Owner = parentWindow, // 设置父窗口
                    WindowStartupLocation = WindowStartupLocation.CenterOwner, // 设置窗口启动位置为父窗口中心
                    Title = $"复议,券码：{trade.Tscode},成交时间：{trade.CreateTime}",
                    Width=560,
                    Height=200
                };
                // 设置关闭窗口的委托
                viewModel.CloseWindowAction = window.Close;
                window.ShowDialog();
            }
            catch(Exception ex)
            {
                AppLog.WriteError($"持仓界面Review异常,{ex.Message},{ex.StackTrace}");
            }
            finally
            {
                blocking = false;
            }
           

        }

        private void ExportHandle(string info)
        {
            try
            {
                switch (info)
                {
                    case "YiPing":
                        this.ExportYiPing();
                        break;
                    case "WeiPing":
                        this.ExportWeiPing();
                        break;
                    case "WeiYue":
                        this.ExportWeiYue();
                        break;
                    default:
                        return;


                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError("OnHoldPositionsViewModel SearchHandle" + ex.Message);
            }
        }

        private void ExportWeiYue()
        {
            
        }

        private void ExportWeiPing()
        {
           
        }
        public void ExportYiPing()
        {
            try
            {
                if (this.YiPingOrder == null || this.YiPingOrder.Count == 0)
                {
                    AppLog.WriteError("无法导出已平持仓，YiPingOrder为空");
                    Growl.WarningGlobal("无法导出已平持仓，数据为空");
                    return;
                }

                var saveFileDialog = new SaveFileDialog
                {
                    Filter = "Excel files (*.xlsx)|*.xlsx",
                    DefaultExt = "xlsx",
                    AddExtension = true,
                    FileName = $"已平持仓_{DateTime.Now:yyyy-MM-dd_HH-mm-ss}"
                };

                if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string filePath = saveFileDialog.FileName;

                    // 设置 EPPlus 许可证上下文
                    ExcelPackage.LicenseContext = LicenseContext.NonCommercial; // 如果你有商业许可证，使用 LicenseContext.Commercial
                    try
                    {
                        using (var package = new ExcelPackage())
                        {
                            var worksheet = package.Workbook.Worksheets.Add($"已平持仓_{DateTime.Now:yyyy-MM-dd}"); // 工作表名称包含日期

                            // 设置列头
                            int columnIndex = 1;
                            worksheet.Cells[1, columnIndex++].Value = "方向";
                            worksheet.Cells[1, columnIndex++].Value = "单据号";
                            worksheet.Cells[1, columnIndex++].Value = "成交价";
                            worksheet.Cells[1, columnIndex++].Value = "备注";
                            worksheet.Cells[1, columnIndex++].Value = "交易员";
                            worksheet.Cells[1, columnIndex++].Value = "清算速度";
                            worksheet.Cells[1, columnIndex++].Value = "已平盈亏";
                            worksheet.Cells[1, columnIndex++].Value = "持仓量";
                            worksheet.Cells[1, columnIndex++].Value = "交易对手";
                            worksheet.Cells[1, columnIndex++].Value = "交割日期";
                            worksheet.Cells[1, columnIndex++].Value = "联系人";
                            worksheet.Cells[1, columnIndex++].Value = "联系方式";
                            worksheet.Cells[1, columnIndex++].Value = "券码";
                            worksheet.Cells[1, columnIndex++].Value = "平仓状态";
                            worksheet.Cells[1, columnIndex++].Value = "成交时间";
                            worksheet.Cells[1, columnIndex++].Value = "交割状态";
                            worksheet.Cells[1, columnIndex++].Value = "修改时间";
                            worksheet.Cells[1, columnIndex++].Value = "研究员";
                            worksheet.Cells[1, columnIndex++].Value = "询价单据号";
                            worksheet.Cells[1, columnIndex++].Value = "交易对手";
                            worksheet.Cells[1, columnIndex++].Value = "中介";

                            // 设置列宽
                            worksheet.Column(2).Width = 25; // 单据号
                            worksheet.Column(4).Width = 25; // 备注
                            worksheet.Column(6).Width = 20; // 清算速度
                            worksheet.Column(7).Width = 16; // 已平盈亏
                            worksheet.Column(9).Width = 16; // 交易对手
                            worksheet.Column(10).Width = 20; // 交割日期
                            worksheet.Column(13).Width = 15; // 券码
                            worksheet.Column(14).Width = 16; // 平仓状态
                            worksheet.Column(15).Width = 20; // 成交时间
                            worksheet.Column(16).Width = 16; // 交割状态
                            worksheet.Column(19).Width = 20; // 询价单据号
                            worksheet.Column(20).Width = 16; // 交易对手

                            // 添加数据行
                            int rowIndex = 2;
                            string lastFinishCode = null;
                            bool isFirstInGroup = true;
                            bool isFirstGroupColor = true;
                            var groupColor1 = System.Drawing.Color.LightGray;
                            var groupColor2 = System.Drawing.Color.White;
                            foreach (var item in YiPingOrder)
                            {
                                columnIndex = 1;
                                worksheet.Cells[rowIndex, columnIndex++].Value = item.Direction == "bond_0" ? "买入" : "卖出";
                                worksheet.Cells[rowIndex, columnIndex++].Value = item.TradeNum;
                                worksheet.Cells[rowIndex, columnIndex++].Value = item.Price;
                                worksheet.Cells[rowIndex, columnIndex++].Value = item.Remark;
                                worksheet.Cells[rowIndex, columnIndex++].Value = item.Tradeuser;
                                worksheet.Cells[rowIndex, columnIndex++].Value = item.DeliverySpeed;
                                worksheet.Cells[rowIndex, columnIndex++].Value = item.Profit;
                                worksheet.Cells[rowIndex, columnIndex++].Value = item.Volume;
                                worksheet.Cells[rowIndex, columnIndex++].Value = item.CounterParty;
                                worksheet.Cells[rowIndex, columnIndex++].Value = item.DeliveryTime;
                                worksheet.Cells[rowIndex, columnIndex++].Value = item.ContactPerson;
                                worksheet.Cells[rowIndex, columnIndex++].Value = item.ContactType;
                                worksheet.Cells[rowIndex, columnIndex++].Value = item.Tscode;
                                worksheet.Cells[rowIndex, columnIndex++].Value = TradeStatusHelper.GetStatusText(item.Status);
                                worksheet.Cells[rowIndex, columnIndex++].Value = item.CreateTime;
                                worksheet.Cells[rowIndex, columnIndex++].Value = JiaoGeStatusConverter.GetRealJiaoGeStatus(item.JiaogeStatus);
                                worksheet.Cells[rowIndex, columnIndex++].Value = item.UpdateTime;
                                worksheet.Cells[rowIndex, columnIndex++].Value = item.YanjiuyuanName;
                                worksheet.Cells[rowIndex, columnIndex++].Value = item.UserTradeNum;
                                worksheet.Cells[rowIndex, columnIndex++].Value = item.CounterParty;
                                // worksheet.Cells[rowIndex, columnIndex++].Value = item.BrokerName;

                                // 设置背景色
                                // 设置背景色
                                if (item.FinishCode != lastFinishCode)
                                {
                                    // 新的 FinishCode 组
                                    isFirstInGroup = true;
                                    isFirstGroupColor = !isFirstGroupColor;
                                    lastFinishCode = item.FinishCode;
                                }

                                // 设置当前行的背景色
                                worksheet.Cells[rowIndex, 1, rowIndex, columnIndex - 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
                                worksheet.Cells[rowIndex, 1, rowIndex, columnIndex - 1].Style.Fill.BackgroundColor.SetColor(isFirstGroupColor ? groupColor1 : groupColor2);
                                // 设置边框
                                worksheet.Cells[rowIndex, 1, rowIndex, columnIndex - 1].Style.Border.Top.Style = ExcelBorderStyle.Thin;
                                worksheet.Cells[rowIndex, 1, rowIndex, columnIndex - 1].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
                                worksheet.Cells[rowIndex, 1, rowIndex, columnIndex - 1].Style.Border.Left.Style = ExcelBorderStyle.Thin;
                                worksheet.Cells[rowIndex, 1, rowIndex, columnIndex - 1].Style.Border.Right.Style = ExcelBorderStyle.Thin;
                                rowIndex++;
                            }

                            // 设置条件格式
                            string profitRange = $"G2:G{rowIndex - 1}"; // “已平盈亏”列范围
                            var greaterThanRule = worksheet.ConditionalFormatting.AddGreaterThan(profitRange);
                            greaterThanRule.Formula = "0";
                            greaterThanRule.Style.Font.Color.SetColor(System.Drawing.Color.Red); // 大于0的显示红色

                            var lessThanRule = worksheet.ConditionalFormatting.AddLessThan(profitRange);
                            lessThanRule.Formula = "0";
                            lessThanRule.Style.Font.Color.SetColor(System.Drawing.Color.Green); // 小于0的显示绿色

                            // 保存 Excel 文件
                            var file = new FileInfo(filePath);
                            package.SaveAs(file);
                            Growl.SuccessGlobal($"导出成功！文件位置：{filePath}");
                        }
                    }
                    catch (Exception ex)
                    {
                        // 处理异常
                        MessageBox.Show($"导出到 Excel 时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError("导出已平单异常" + ex.Message + ex.StackTrace);
            }
        }

        //public void ExportYiPing()
        //{
        //    try
        //    {
        //        if (this.YiPingOrder == null || this.YiPingOrder.Count == 0)
        //        {
        //            AppLog.WriteError("无法导出已平持仓，YiPingOrder为空");
        //            Growl.WarningGlobal("无法导出已平持仓，数据为空");
        //            return;
        //        }
        //        var saveFileDialog = new SaveFileDialog
        //        {
        //            Filter = "Excel files (*.xlsx)|*.xlsx",
        //            DefaultExt = "xlsx",
        //            AddExtension = true,
        //            FileName = $"已平持仓_{DateTime.Now:yyyy-MM-dd_HH-mm-ss}"
        //        };

        //        if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        //        {
        //            string filePath = saveFileDialog.FileName;

        //            // 设置 EPPlus 许可证上下文
        //            ExcelPackage.LicenseContext = LicenseContext.NonCommercial; // 如果你有商业许可证，使用 LicenseContext.Commercial
        //            try
        //            {
        //                using (var package = new ExcelPackage())
        //                {
        //                    var worksheet = package.Workbook.Worksheets.Add($"已平持仓_{DateTime.Now:yyyy-MM-dd}"); // 工作表名称包含日期

        //                    // 设置列头
        //                    int columnIndex = 1;
        //                    worksheet.Cells[1, columnIndex++].Value = "方向";
        //                    worksheet.Cells[1, columnIndex++].Value = "单据号";
        //                    worksheet.Cells[1, columnIndex++].Value = "成交价";
        //                    worksheet.Cells[1, columnIndex++].Value = "备注";
        //                    worksheet.Cells[1, columnIndex++].Value = "交易员";
        //                    worksheet.Cells[1, columnIndex++].Value = "清算速度";
        //                    worksheet.Cells[1, columnIndex++].Value = "已平盈亏";
        //                    worksheet.Cells[1, columnIndex++].Value = "持仓量";
        //                    worksheet.Cells[1, columnIndex++].Value = "交易对手";
        //                    worksheet.Cells[1, columnIndex++].Value = "交割日期";
        //                    worksheet.Cells[1, columnIndex++].Value = "联系人";
        //                    worksheet.Cells[1, columnIndex++].Value = "联系方式";
        //                    worksheet.Cells[1, columnIndex++].Value = "券码";
        //                    worksheet.Cells[1, columnIndex++].Value = "平仓状态";
        //                    worksheet.Cells[1, columnIndex++].Value = "成交时间";
        //                    worksheet.Cells[1, columnIndex++].Value = "交割状态";
        //                    worksheet.Cells[1, columnIndex++].Value = "修改时间";
        //                    worksheet.Cells[1, columnIndex++].Value = "研究员";
        //                    worksheet.Cells[1, columnIndex++].Value = "询价单据号";
        //                    worksheet.Cells[1, columnIndex++].Value = "交易对手";
        //                    worksheet.Cells[1, columnIndex++].Value = "中介";


        //                    worksheet.Column(2).Width = 25;//单据号
        //                    worksheet.Column(4).Width = 25;//备注
        //                    worksheet.Column(6).Width = 20;//清算速度
        //                    worksheet.Column(7).Width = 16;//已平盈亏
        //                    worksheet.Column(9).Width = 16;//交易对手
        //                    worksheet.Column(10).Width = 20;//交割日期
        //                    worksheet.Column(13).Width = 15;//券码
        //                    worksheet.Column(14).Width = 16;//平仓状态
        //                    worksheet.Column(15).Width = 20;//成交时间
        //                    worksheet.Column(16).Width = 16;//交割状态
        //                    worksheet.Column(19).Width = 20;//询价单据号
        //                    worksheet.Column(20).Width = 16;//交易对手

        //                    // 添加数据行
        //                    int rowIndex = 2;
        //                    foreach (var item in YiPingOrder)
        //                    {
        //                        columnIndex = 1;
        //                        worksheet.Cells[rowIndex, columnIndex++].Value = item.Direction == "bond_0" ? "买入" : "卖出";
        //                        worksheet.Cells[rowIndex, columnIndex++].Value = item.TradeNum;
        //                        worksheet.Cells[rowIndex, columnIndex++].Value = item.Price;
        //                        worksheet.Cells[rowIndex, columnIndex++].Value = item.Remark;
        //                        worksheet.Cells[rowIndex, columnIndex++].Value = item.Tradeuser;
        //                        worksheet.Cells[rowIndex, columnIndex++].Value = item.DeliverySpeed;
        //                        worksheet.Cells[rowIndex, columnIndex++].Value = item.Profit;
        //                        worksheet.Cells[rowIndex, columnIndex++].Value = item.Volume;
        //                        worksheet.Cells[rowIndex, columnIndex++].Value = item.CounterParty;
        //                        worksheet.Cells[rowIndex, columnIndex++].Value = item.DeliveryTime;
        //                        worksheet.Cells[rowIndex, columnIndex++].Value = item.ContactPerson;
        //                        worksheet.Cells[rowIndex, columnIndex++].Value = item.ContactType;
        //                        worksheet.Cells[rowIndex, columnIndex++].Value = item.Tscode;
        //                        worksheet.Cells[rowIndex, columnIndex++].Value = TradeStatusHelper.GetStatusText(item.Status);
        //                        worksheet.Cells[rowIndex, columnIndex++].Value = item.CreateTime;
        //                        worksheet.Cells[rowIndex, columnIndex++].Value = JiaoGeStatusConverter.GetRealJiaoGeStatus(item.JiaogeStatus);
        //                        worksheet.Cells[rowIndex, columnIndex++].Value = item.UpdateTime;
        //                        worksheet.Cells[rowIndex, columnIndex++].Value = item.YanjiuyuanName;
        //                        worksheet.Cells[rowIndex, columnIndex++].Value = item.UserTradeNum;
        //                        worksheet.Cells[rowIndex, columnIndex++].Value = item.CounterParty;
        //                        //worksheet.Cells[rowIndex, columnIndex++].Value = item.BrokerName;

        //                        rowIndex++;
        //                    }
        //                    // 设置条件格式
        //                    string profitRange = $"G2:G{rowIndex - 1}"; // “已平盈亏”列范围
        //                    var greaterThanRule = worksheet.ConditionalFormatting.AddGreaterThan(profitRange);
        //                    greaterThanRule.Formula = "0";
        //                    greaterThanRule.Style.Font.Color.SetColor(System.Drawing.Color.Red); // 大于0的显示红色

        //                    var lessThanRule = worksheet.ConditionalFormatting.AddLessThan(profitRange);
        //                    lessThanRule.Formula = "0";
        //                    lessThanRule.Style.Font.Color.SetColor(System.Drawing.Color.Green); // 小于0的显示绿色
        //                    // 保存 Excel 文件
        //                    var file = new FileInfo(filePath);
        //                    package.SaveAs(file);
        //                    //MessageBox.Show("导出成功！", "信息", MessageBoxButton.OK, MessageBoxImage.Information);
        //                    Growl.SuccessGlobal($"导出成功！文件位置：{filePath}");
        //                }
        //            }
        //            catch (Exception ex)
        //            {
        //                // 处理异常
        //                MessageBox.Show($"导出到 Excel 时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        //            }
        //        }

        //    }
        //   catch(Exception ex)
        //    {
        //        AppLog.WriteError("导出已平单异常" + ex.Message + ex.StackTrace);
        //    }
        //}

        private void SearchHandle(string info)
        {
            try
            {
                switch(info)
                {
                    case "YiPing":
                        lock(_lockObj)
                        {
                            this.InitYiPingValueAsync();
                        }
                      
                        break;
                    case "WeiPing":
                        lock (_lockObj)
                        {
                            this.InitWeiPingValueAsync();
                        }
                  
                        break;
                    case "WeiYue":
                        lock (_lockObj)
                        {
                            this.InitWeiYueValueAsync();
                        }
               
                        break;
                    default:
                        return;


                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError("OnHoldPositionsViewModel SearchHandle" + ex.Message);
            }
        }

        public event EventHandler<ChangePriceArgs> PingCangRequested;
      

        private void PingCangHandle(object? sender, PingCangArgs e)
        {
            if(OrderListViewModel.websocket!=null)
            {
                QuanYiOrderServerResponseClass qsr = new QuanYiOrderServerResponseClass();
                qsr.Trade = e.Trade;
                qsr.DataType = QuanYiServerBaseClass.DataTypeEnum.PingCang;
                OrderListViewModel.websocket.SendResponseToServer(qsr);
            }
        }

        private async Task InitValueAsync()
        {
            try
            {
                var weiYueTask = InitWeiYueValueAsync();//违约单
                var yiPingTask = InitYiPingValueAsync();//已平单
                var weiPingTask = InitWeiPingValueAsync();//未平单

                // 等待所有任务完成
                await Task.WhenAll(weiYueTask, yiPingTask, weiPingTask);
                //var allNoPingCangOrder = UserHelper.SearchAllNoPingCangOrder().TradeRows;
                ////this.OnHoldPingCangLilyList = 
                //HoldType = new ObservableCollection<string>() { "全部", "待平仓", "已平仓" };
                //// 获取用户交易数据
                //var tempOnHoldDataList = _dailyData.GetUserTrades(UserHelper.UserID).ToList();

                //var tsInfos = OrderListViewModel.LazyTsInfoStaticList;

                //var tsTypes = OrderListViewModel.LazyTsTypeStaticList;
                //// 使用并行处理进行数据转换
                //var updatedTrades = tempOnHoldDataList.AsParallel().Select(trade =>
                //{
                //    var tsInfo = tsInfos.FirstOrDefault(ts => ts.Tscode == trade.TsCode);

                //    if (tsInfo != null)
                //    {
                //        var matchingTsType = tsTypes.FirstOrDefault(type => tsInfo.Bondname.Contains(type));
                //        return new UserTrade
                //        {
                //            TsCode = trade.TsCode,
                //            TsCodeType = matchingTsType ?? tsInfo.Bondname, // Use matchingTsType if found, otherwise Bondname,
                //            TsCodeTerm = tsInfo.Maturity,
                //            PVBP = (decimal)tsInfo.Basicvalue,

                //            // 保留原有属性
                //            UserTradeID = trade.UserTradeID,
                //            Price = trade.Price,
                //            Volume = trade.Volume,
                //            Broker = trade.Broker,
                //            ChatID = trade.ChatID,
                //            UserID = trade.UserID,
                //            Status = trade.Status,
                //            DealType = trade.DealType,
                //            DeliveryDate = trade.DeliveryDate,
                //            Time = trade.Time,
                //            ReceiverId = trade.ReceiverId,
                //            Id = trade.Id,
                //            Target = trade.Target,
                //            Command = trade.Command,
                //            UserName = trade.UserName,
                //            OrderType = trade.OrderType,
                //            Guid = trade.Guid,
                //            DailyID = trade.DailyID,
                //            OnHoldVolume = trade.OnHoldVolume,
                //            BrokerID = trade.BrokerID,
                //            StatusText = trade.StatusText,
                //            BrokerDetailInfo = trade.BrokerDetailInfo
                //        };
                //    }
                //    else
                //    {
                //        // 如果找不到对应的 Tsinfo，则不进行转换，可以根据业务需求处理
                //        return null;
                //    }
                //})
                //.Where(trade => trade != null) // 过滤掉未成功转换的条目
                //.ToList();

                //switch(SelectedHoldTypeIndex)
                //{
                //    ///全部
                //    case 0:
                //        updatedTrades = updatedTrades.Where(o => o.Status == 11|| o.Status == 12).ToList();
                //        break;
                //    ///待平仓
                //    case 1:
                //        updatedTrades = updatedTrades.Where(o => o.Status == 11).ToList();
                //        break;
                //    ///已平仓
                //    case 2:
                //        updatedTrades = updatedTrades.Where(o => o.Status == 12).ToList();
                //        break;

                //}
                //// 转换为 ObservableCollection 并赋值给 OnHoldDataList
                //OnHoldDataList = new ObservableCollection<UserTrade>(updatedTrades);
            }
            catch (Exception ex)
            {
                AppLog.WriteError("OnHoldPositionsViewModel InitValue异常" + ex.Message);
            }
        }

        /// <summary>
        /// 初始化所有违约单
        /// </summary>
        /// <returns></returns>
        public async Task InitWeiYueValueAsync()
        {
            try
            {
                IsLoading = true;
                var startTime = DateTime.Now;
                // 直接调用异步方法
                var weiYueResult = await UserHelper.SearchAllWeiYueAsync();

                if(weiYueResult==null||weiYueResult.Value.Count==0)
                {
                    if(this.WeiYueTrades!=null)
                    {
                        this.WeiYueTrades.Clear();
                    }else
                    {

                    }
                    return;
                    
                }
                // 确保数据在 UI 线程上更新
               await PrismApplication.Current.Dispatcher.InvokeAsync(() =>
                {
                    this.WeiYueTrades = new ObservableCollection<WeiYueChildTrade>(weiYueResult.Value);
                });

                var endTime = DateTime.Now;
                var duration = endTime - startTime;
                AppLog.WriteInfo($"违约单加载 耗时: {duration.TotalMilliseconds} 毫秒");
            }
            catch (Exception ex)
            {
                // 处理异常
                AppLog.WriteError($"违约单Error: {ex.Message},{ex.StackTrace}");
            }
            finally
            {
                IsLoading = false;
            }
        }


        /// <summary>
        /// 初始化所有未平仓单
        /// </summary>
        /// <returns></returns>
        /// 
        public async Task InitWeiPingValueAsync()
        {
            try
            {
                IsLoading = true;
                var startTime = DateTime.Now;
                // 获取数据
                var result = await Task.Run(async () =>
                {
                    var tradeData = await UserHelper.SearchAllNoPingCangOrderAsync();
                    if(tradeData==null)
                    {
                        return null;
                    }
                    if (tradeData.TradeRows!=null)
                    {
                        return tradeData.TradeRows.ToObservableCollection();
                    }
                    else
                    {
                        //Growl.InfoGlobal("暂未查询到未平仓单");
                        AppLog.WriteInfo("未查询到未平仓单！");
                        if(WeiPingOrder!=null)
                        {
                            PrismApplication.Current.Dispatcher.Invoke(() =>
                            {
                                this.WeiPingOrder.Clear();
                                this.WeiPingOrder = null;
                                this.WeiPingBuyVolume = 0;
                                this.WeiPingSellVolume = 0;
                                this.WeiPingYingKui = 0;
                            });
                        }else
                        {
                            PrismApplication.Current.Dispatcher.Invoke(() =>
                            {
                                this.WeiPingBuyVolume = 0;
                                this.WeiPingSellVolume = 0;
                                this.WeiPingYingKui = 0;
                            });
                         
                        }
                     
                      
                        return null;
                    }
                });

                if (result != null)
                {
                    // 确保数据在 UI 线程上更新
                    await PrismApplication.Current.Dispatcher.InvokeAsync(() =>
                    {
                        this.WeiPingOrder = new ObservableCollection<PingCangLilyTrade>(result);
                    });


                    foreach(var weipingOrderItem in WeiPingOrder)
                    {
                        if(weipingOrderItem.Children!=null&&string.IsNullOrEmpty(weipingOrderItem.DeliverySpeed))
                        {
                            weipingOrderItem.DeliverySpeed = weipingOrderItem.Children[0].DeliverySpeed;
                        }
                    }
                    // 后台线程进行计算
                    this.WeiPingYingKui = Math.Round(WeiPingOrder
                        .Where(o => o.FloatProfit != null) // 过滤掉 FloatProfit 为 null 的项
                        .Sum(o => (decimal)o.FloatProfit), 2);

                    // 计算 WeiPingBuyVolume
                    this.WeiPingBuyVolume = WeiPingOrder
                        .Where(o => o.Direction == "bond_0")
                        .Sum(o =>
                        {
                            if (decimal.TryParse(o.Volume, out decimal volumeDecimal))
                            {
                                return (long)volumeDecimal;
                            }
                            else
                            {
                                return 0L; // 默认返回值，或者根据具体情况进行处理
                            }
                        });

                    // 计算 WeiPingSellVolume
                    this.WeiPingSellVolume = WeiPingOrder
                        .Where(o => o.Direction == "bond_1")
                        .Sum(o =>
                        {
                            if (decimal.TryParse(o.Volume, out decimal volumeDecimal))
                            {
                                return (long)volumeDecimal;
                            }
                            else
                            {
                                return 0L; // 默认返回值，或者根据具体情况进行处理
                            }
                        });

                    var endTime = DateTime.Now;
                    var duration = endTime - startTime;
                    AppLog.WriteInfo($"未平仓单加载 耗时: {duration.TotalMilliseconds} 毫秒");

                    Messenger.Default.Send("null",MessageToken.ExpandWeiPing);
                }


            }
            catch (Exception ex)
            {
                // 处理异常
                AppLog.WriteError($"未平仓单Error: {ex.Message},{ex.StackTrace}");
            }
            finally
            {
                IsLoading = false;
            }
        }

        //public async Task InitWeiPingValueAsync()
        //{
        //    try
        //    {
        //        var result = await Task.Run(() =>
        //        {
        //            // 确保 UserHelper.SearchAllWeiYue().Value 返回正确的数据
        //            if (UserHelper.SearchAllNoPingCangOrder() != null)
        //            {
        //                return UserHelper.SearchAllNoPingCangOrder().TradeRows.ToObservableCollection();
        //            }
        //            else
        //            {
        //                //Growl.InfoGlobal("暂未查询到未平仓单");
        //                return null;
        //            }

        //        });


        //        // 确保数据在 UI 线程上更新
        //       await PrismApplication.Current.Dispatcher.InvokeAsync(() =>
        //        {
        //            this.WeiPingOrder = new ObservableCollection<PingCangLilyTrade>(result);
        //        });

        //        this.WeiPingYingKui = Math.Round(WeiPingOrder
        //            .Where(o => o.FloatProfit != null) // 过滤掉 FloatProfit 为 null 的项
        //            .Sum(o => (decimal)o.FloatProfit), 2);

        //        // 使用 LINQ 查询计算总和时，先将 Volume 字符串转换为 decimal 类型
        //        this.WeiPingBuyVolume = WeiPingOrder
        //            .Where(o => o.Direction == "bond_0")
        //            .Sum(o =>
        //            {
        //                if (decimal.TryParse(o.Volume, out decimal volumeDecimal))
        //                {
        //                    return (long)volumeDecimal;
        //                }
        //                else
        //                {
        //                    // 处理无法转换的情况，例如抛出异常或者返回默认值
        //                    return 0L; // 默认返回值，或者根据具体情况进行处理
        //                }
        //            });
        //        // 使用 LINQ 查询计算总和时，先将 Volume 字符串转换为 decimal 类型
        //        this.WeiPingSellVolume = WeiPingOrder
        //            .Where(o => o.Direction == "bond_1")
        //            .Sum(o =>
        //            {
        //                if (decimal.TryParse(o.Volume, out decimal volumeDecimal))
        //                {
        //                    return (long)volumeDecimal;
        //                }
        //                else
        //                {
        //                    // 处理无法转换的情况，例如抛出异常或者返回默认值
        //                    return 0L; // 默认返回值，或者根据具体情况进行处理
        //                }
        //            });
        //    }
        //    catch (Exception ex)
        //    {
        //        // 处理异常
        //        Console.WriteLine($"Error: {ex.Message}");
        //    }
        //}

        /// <summary>
        /// 初始化所有未平仓单
        /// </summary>
        /// <returns></returns>
        public async Task InitYiPingValueAsync()
        {
            try
            {
                IsLoading = true;
                var startTime = DateTime.Now;
                var result = await Task.Run(async () =>
                {
                    // 将方法结果存储在局部变量中
                    var pingCangOrder =await UserHelper.SearchAllPingCangOrder();

                    // 判断结果是否为 null
                    if (pingCangOrder != null)
                    {
                        return pingCangOrder.ToObservableCollection();
                    }
                    else
                    {
                        // Growl.InfoGlobal("暂未查询到已平仓单");
                        AppLog.WriteInfo("已平单查询为空");
                        if(this.YiPingOrder!= null)
                        {
                            PrismApplication.Current.Dispatcher.Invoke(() =>
                            {
                                this.YiPingOrder.Clear();
                                this.YiPingOrder = null;
                                this.YiPingBuyVolume = 0;
                                this.YiPingSellVolume = 0;
                                this.YiPingYingKui = 0;
                            });
                        }else
                        {
                            PrismApplication.Current.Dispatcher.Invoke(() =>
                            {
                                this.YiPingBuyVolume = 0;
                                this.YiPingSellVolume = 0;
                                this.YiPingYingKui = 0;
                            });
                          
                        }
                       
                        return null;
                    }
                });
                if (result == null)
                {
                    return;
                }
                var temp = result.OrderByDescending(item => item.CreateTime).ToList();
                // 为了按照 FinishCode 的值进行分组，需要先对数据进行排序
                var sortedResult = temp.OrderByDescending(item => item.FinishCode).ToList();

                string currentFinishCode = null;
                bool flag = false;

                foreach (var item in sortedResult)
                {
                    if (item.FinishCode != currentFinishCode)
                    {
                        // 遇到新的 FinishCode，切换 flag 值
                        flag = !flag;
                        currentFinishCode = item.FinishCode;
                    }
                    // 设置 Flag 的值
                    item.Flag = flag;
                }
                // 确保数据在 UI 线程上更新
                PrismApplication.Current.Dispatcher.Invoke(() =>
                {
                    this.YiPingOrder = new ObservableCollection<YiPingLilyTrade>(sortedResult);

                    var pairedTrades = this.YiPingOrder
                        .GroupBy(t => new { t.FinishCode, t.DeliverySpeed, t.Price, t.Tscode })
                        .SelectMany(g => g
                            .Where(t => g.Any(t2 => t2.Direction != t.Direction &&
                                                    t2.FinishCode == t.FinishCode &&
                                                    t2.DeliverySpeed == t.DeliverySpeed &&
                                                    t2.Price == t.Price &&
                                                    t2.Tscode == t.Tscode)))
                        .ToList();

                    if(pairedTrades!=null&&pairedTrades.Count>0)
                    {
                        this.DuiChongOrder = new ObservableCollection<YiPingLilyTrade>(pairedTrades);

                        this.DuiChongYingKui = Math.Round(DuiChongOrder
            .Where(o => o.Profit != null)
            .Sum(o => (decimal)o.Profit), 2);

                        // 使用 LINQ 查询计算总和时，先将 Volume 字符串转换为 decimal 类型
                        this.DuiChongBuyVolume = DuiChongOrder
                            .Where(o => o.Direction == "bond_0")
                            .Sum(o =>
                            {
                                if (decimal.TryParse(o.Volume, out decimal volumeDecimal))
                                {
                                    return (long)volumeDecimal;
                                }
                                else
                                {
                                    // 处理无法转换的情况，例如抛出异常或者返回默认值
                                    return 0L; // 默认返回值，或者根据具体情况进行处理
                                }
                            });
                        // 使用 LINQ 查询计算总和时，先将 Volume 字符串转换为 decimal 类型
                        this.DuiChongSellVolume = DuiChongOrder
                            .Where(o => o.Direction == "bond_1")
                            .Sum(o =>
                            {
                                if (decimal.TryParse(o.Volume, out decimal volumeDecimal))
                                {
                                    return (long)volumeDecimal;
                                }
                                else
                                {
                                    // 处理无法转换的情况，例如抛出异常或者返回默认值
                                    return 0L; // 默认返回值，或者根据具体情况进行处理
                                }
                            });
                    }else
                    {
                        if(this.DuiChongOrder!=null)
                        {
                            this.DuiChongOrder.Clear();
                            PrismApplication.Current.Dispatcher.Invoke(() =>
                            {
                                this.DuiChongBuyVolume = 0;
                                this.DuiChongSellVolume = 0;
                                this.DuiChongYingKui = 0;
                            });
                        }
                 
                    }
                  


                });
                // 筛选成对的交易
            


                this.YiPingYingKui = Math.Round(YiPingOrder
    .Where(o => o.Profit != null)
    .Sum(o => (decimal)o.Profit), 2);

                // 使用 LINQ 查询计算总和时，先将 Volume 字符串转换为 decimal 类型
                this.YiPingBuyVolume = YiPingOrder
                    .Where(o => o.Direction == "bond_0")
                    .Sum(o =>
                    {
                        if (decimal.TryParse(o.Volume, out decimal volumeDecimal))
                        {
                            return (long)volumeDecimal;
                        }
                        else
                        {
                            // 处理无法转换的情况，例如抛出异常或者返回默认值
                            return 0L; // 默认返回值，或者根据具体情况进行处理
                        }
                    });
                // 使用 LINQ 查询计算总和时，先将 Volume 字符串转换为 decimal 类型
                this.YiPingSellVolume = YiPingOrder
                    .Where(o => o.Direction == "bond_1")
                    .Sum(o =>
                    {
                        if (decimal.TryParse(o.Volume, out decimal volumeDecimal))
                        {
                            return (long)volumeDecimal;
                        }
                        else
                        {
                            // 处理无法转换的情况，例如抛出异常或者返回默认值
                            return 0L; // 默认返回值，或者根据具体情况进行处理
                        }
                    });

                var endTime = DateTime.Now;
                var duration = endTime - startTime;
                AppLog.WriteError($"已平仓单-耗时: {duration.TotalMilliseconds} 毫秒");

            }
            catch (Exception ex)
            {
                // 处理异常
                AppLog.WriteError($"已平仓单Error: {ex.Message},{ex.StackTrace}");
            }
            finally
            {
                IsLoading = false;
            }
        }

        #region 对接我服务端的操作
        /// <summary>
        /// 打开平仓界面
        /// </summary>
        /// <param name="trade"></param>
        private void OpenPingCangViewHandle(PingCangLilyTrade trade)
        {
            if(OrderListViewModel.userStatus==2)
            {
                Growl.WarningGlobal("当前状态异常，无法平仓！");
                return;
            }

         
            if (trade != null && trade.Children != null)
            {
                List<int> realTradeIds = new List<int>();

                foreach (var child in trade.Children)
                {
                    realTradeIds.Add((int)child.RealTradeId);
                }

                int[] realTradeIdArray = realTradeIds.ToArray();


                var viewModel = new PingCangViewModel(trade,_dailyData);

                viewModel.PingCangRequested -= PingCangHandle;
                viewModel.PingCangRequested += PingCangHandle;
                var parentWindow = PrismApplication.Current.Windows.OfType<OnHoldPositionsView>().FirstOrDefault(w => w.IsActive);
                // 创建新窗口并设置DataContext
                //var window = new PingCangView
                //{
                //    DataContext = viewModel,
                //    Owner = parentWindow, // 设置父窗口
                //    WindowStartupLocation = WindowStartupLocation.CenterOwner // 设置窗口启动位置为父窗口中心
                //};
                //window.ShowDialog();
                var pingCangView = PingCangView.GetInstance(viewModel, parentWindow);
                pingCangView.Show();
                // 现在 realTradeIdArray 就是包含所有 Children 中 RealTradeId 的 int 数组
                // 可以在这里使用 realTradeIdArray 进行后续操作
            }
        }
        /// <summary>
        /// 执行平仓
        /// </summary>
        private void PingCang(PingCangLilyTrade userTrade)
        {
            
            ////if (userTrade != null)
            ////{
            ////    if (userTrade.Status != 0 & userTrade.Status != 1 & userTrade.Status != 4 & userTrade.Status != 7 & userTrade.Status != 23)
            ////    {
            ////        MessageBox.Show("该单状态不对，无法平仓", "Error");
            ////        return;
            ////    }
            ////}
            //var viewModel = new PingCangViewModel(userTrade);
            //viewModel.ChangePriceRequested -= ChangePrice;
            //viewModel.ChangePriceRequested += ChangePrice;
            //var parentWindow = PrismApplication.Current.MainWindow;

            //// 创建新窗口并设置DataContext
            //var window = new ChangePriceView
            //{
            //    DataContext = viewModel,
            //    Owner = parentWindow, // 设置父窗口
            //    WindowStartupLocation = WindowStartupLocation.CenterOwner, // 设置窗口启动位置为父窗口中心
            //    Title = $"改价窗口,券码：{userTrade.TsCode},下单时间：{userTrade.Time}"
            //};
            //window.ShowDialog();

        }

        private async void ChangePrice(object? sender, ChangePriceArgs e)
        {
            //try
            //{
            //    var newTrade = e.Trade;
            //    if (await SendModify(selectedUserTrade, newTrade))
            //    {
            //        //AppLog.WriteInfo("改价成功!"+newTrade.ToString());
            //        //MessageBox.Show("改价成功");
            //    }
            //    else
            //    {
            //        AppLog.WriteError("改价失败：");
            //    }

            //}
            //catch (Exception ex)
            //{
            //    AppLog.WriteError("改价异常：" + ex.StackTrace + ex.Message);
            //}
            //finally
            //{
            //    this.SearchHandle();
            //}

        }
        //private async Task<bool> SendModify(UserTrade olduserTrade, UserTrade newuserTrade)
        //{

        //    var tempTsInfo = _dailyData.GetBondByCode(olduserTrade.TsCode);
        //    decimal CurrentPrice = _dailyData.GetLatestPrice(tempTsInfo, false);

        //    string orderDeliveryInfo = olduserTrade.DealType;
        //    string order = $"{olduserTrade.DealType} {olduserTrade.TsCode.Replace(".IB", "")} 改 {newuserTrade.Price}";

        //    if (orderDeliveryInfo == "bid") //买单，所以改-现在必须>0.25
        //    {
        //        if (CurrentPrice - newuserTrade.Price > 0.0025M)
        //        {
        //            var result = MessageBox.Show("是否确认改价？当前是买单---当前价差超过0.25BP \r\n" + order.Replace("{ADD}", "+"), "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
        //        }
        //        else
        //        {
        //            var result = MessageBox.Show("是否改价？ \r\n" + order.Replace("{ADD}", "+"), "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
        //            if (result == MessageBoxResult.No)
        //            {
        //                blocking = false;
        //                AppLog.WriteInfo("用户取消改价了");
        //                return false;
        //            }
        //        }
        //    }
        //    else
        //    {
        //        if (newuserTrade.Price - CurrentPrice > 0.0025M)
        //        {
        //            var result = MessageBox.Show("是否确认改价？当前是卖单---当前价差超过0.25BP \r\n" + order.Replace("{ADD}", "+"), "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
        //        }
        //        else
        //        {
        //            var result = MessageBox.Show("是否改价？ \r\n" + order.Replace("{ADD}", "+"), "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
        //            if (result == MessageBoxResult.No)
        //            {
        //                blocking = false;
        //                AppLog.WriteInfo("用户取消改价了");
        //                return false;
        //            }
        //        }
        //    }



        //    //if (Math.Abs(tPrice.Value - CurrentPrice) > 0.006M)
        //    //{
        //    //    if (MessageBox.Show("下单价与当前价差超过0.6BP，是否下单？ \r\n", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
        //    //    {
        //    //        return;
        //    //    }
        //    //}
        //    QuanYiOrderServerResponseClass qsr = new QuanYiOrderServerResponseClass();
        //    CurrentGuid = Guid.NewGuid();
        //    qsr.DataType = QuanYiServerBaseClass.DataTypeEnum.ChangePrice;
        //    //QCT.Command = order;
        //    //QCT.Price = newuserTrade.Price;
        //    qsr.Trade = newuserTrade;
        //    qsr.Trade.ChatID = UserHelper.UserID.ToString();
        //    qsr.Guid = CurrentGuid;
        //    qsr.Token = UserHelper.Token;
        //    qsr.Trade.BrokerID = 2;
        //    string msg;
        //    try
        //    {
        //        if (bIsConnected)
        //        {
        //            //bResponseReceived = false;
        //            //clientWebsocket.SendResponseToServer(qsr);
        //            //IsLoading = true;
        //            //Task.Run(() =>
        //            //{
        //            //    WaitingResponseThread();
        //            //});

        //            bResponseReceived = false;
        //            blocking = true;
        //            IsLoading = true;
        //            LoadingMessage = "正在发送改价指令...";
        //            websocket.SendResponseToServer(qsr);
        //            await WaitForWebSocketResponse(); // 等待 WebSocket 响应

        //            if (GlobalQSR.Code != 0)
        //            {
        //                MessageBox.Show("风控没通过，请检查价格。" + GlobalQSR.Message);
        //                IsLoading = false;
        //                blocking = false;
        //                return false;
        //            }
        //            IsLoading = false;
        //            blocking = false;
        //            LoadingMessage = "发送成功!";
        //        }
        //        else
        //        {
        //            Growl.ErrorGlobal("连接失败，请检查");
        //            blocking = false;
        //            AppLog.WriteError($"下单：微信下单失败,{QCT.Command},{QCT.Target}");
        //            return false;
        //        }
        //    }
        //    catch
        //    {
        //        MessageBox.Show("无法连接服务器，请联系管理员！", "Error");
        //        AppLog.WriteError($"下单：微信下单失败,{QCT.Command},{QCT.Target}");
        //        return false;
        //    }


        //    var result1 = MessageBox.Show("中介是否允许改价？", "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
        //    if (result1 == MessageBoxResult.No)
        //    {
        //        blocking = false;
        //        QCT.Price = olduserTrade.Price;
        //        AppLog.WriteInfo($"中介拒绝改价,{QCT.Command},{QCT.Target}" + olduserTrade.UserTradeID.ToString());
        //        return false;
        //    }
        //    else
        //    {
        //        CurrentGuid = Guid.NewGuid();
        //        qsr.DataType = QuanYiServerBaseClass.DataTypeEnum.ChangePriceConfirm;
        //        qsr.Code = 0;
        //        qsr.Trade = newuserTrade;
        //        qsr.Token = UserHelper.Token;
        //        qsr.Guid = CurrentGuid;
        //    }


        //    try
        //    {
        //        if (bIsConnected)
        //        {
        //            bResponseReceived = false;
        //            blocking = true;
        //            IsLoading = true;
        //            LoadingMessage = "正在发送确认改价指令...";
        //            websocket.SendResponseToServer(qsr);
        //            await WaitForWebSocketResponse(); // 等待 WebSocket 响应

        //            IsLoading = false;

        //            LoadingMessage = "发送成功!";
        //            blocking = false;
        //        }
        //        else
        //        {
        //            blocking = false;
        //            MessageBox.Show("无法连接发送服务器，请联系管理员");
        //            AppLog.WriteError($"下单：微信下单失败,{QCT.Command},{QCT.Target}");
        //            return false;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        blocking = false;
        //        Growl.ErrorGlobal("无法连接服务器，请联系管理员！" + ex.Message);
        //        //MessageBox.Show("无法连接发送服务器，请联系管理员");
        //        AppLog.WriteError($"下单：微信下单失败,{QCT.Command},{QCT.Target}");
        //        return false;
        //    }
        //    finally
        //    {

        //    }
        //    return true;
        //}
        #endregion

    }
}
